using UnityEngine;
using System.Collections;
using LitJson;

public class NickNameInput : MonoBehaviour {
	public CharacterSelectSceneManager manager;
	
	public GameObject nickNameLabel;
	public UILabel recommendFriendNameLabel;

	private bool m_submit = false;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void OnSubmit()
	{
		string nickName = nickNameLabel.GetComponent<UILabel>().text;
		int nLength = nickName.Length;
		char[] trimChar = { '|', '\r' };
		nickName = nickName.TrimEnd(trimChar);
		if( nickName != null )
			manager.CreateUser(nickName);
//        StartCoroutine("WebRequestPost");
	}

    IEnumerator WebRequestPost()
    {
		if (!m_submit)
		{
			m_submit = true;
			string nickName = nickNameLabel.GetComponent<UILabel>().text;
			int nLength = nickName.Length;
			char[] trimChar = { '|', '\r' };
			nickName = nickName.TrimEnd(trimChar);
			
			LoadingWindow.window.ShowShortLoading();
			RestAPI.singleton.CreateUser(ReturnCallback, nickName, 1);
			yield return null;
		}
    }
				
	void ReturnCallback(Hashtable returnData)
	{
		switch((RestAPIProtocol)returnData["protocol"])
		{
		case RestAPIProtocol.CREATEUSER:
			string recommendFriendName = recommendFriendNameLabel.text;
			if( recommendFriendName != null && recommendFriendName != "" )
			{
				recommendFriendName = recommendFriendName.Trim();

                LoadingWindow.window.ShowShortLoading();
				RestAPI.singleton.SendReferralInfo(ReturnCallback, recommendFriendName);
			}
			else
			{
				CSceneManager.SendLoginPacket();
			}
			break;
		case RestAPIProtocol.SENDREFERRALINFO:
			CSceneManager.SendLoginPacket();
			break;
		}
	}
}
